package com.vivo.tasks;

import com.thinkgem.jeesite.common.utils.StringUtils;
import com.vivo.dingtalk.auth.AuthHelper;
import com.vivo.system.entity.VivoDingConf;
import com.vivo.system.service.VivoDingConfService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;


/**
 * 定时刷新钉钉accesstoken
 */
@Component
public class TaskUpdDingAccessToken {

    @Autowired
    private VivoDingConfService dingConfService;

    public void SyncData() {
        // 获取所有公司钉钉配置信息
        List<VivoDingConf> dingConfList = dingConfService.findList(new VivoDingConf());

        for (VivoDingConf dingConf: dingConfList) {

            // 获取access_token
            String accessToken = null;
            String ticket = null;

            long timeOut = 1000 * 60 * 55 * 2;
            Date dateNow = new Date();
            long curTime = dateNow.getTime();

            if (StringUtils.isBlank(dingConf.getAccessToken()) ||
                    dingConf.getAccTokenTime() == null ||
                    curTime - dingConf.getAccTokenTime().getTime() >= timeOut) {
                try {
                    accessToken = AuthHelper.getAccessToken(dingConf.getCorpId(), dingConf.getCorpSecret());
                    ticket = AuthHelper.getJsapiTicket(accessToken);

                    if (accessToken != null && ticket != null) {
                        dingConf.setAccessToken(accessToken);
                        dingConf.setAccTokenTime(dateNow);
                        dingConf.setTicket(ticket);
                        dingConf.setTicketTime(dateNow);
                    }
                }catch (Exception e) {
                    e.printStackTrace();
                    dingConf.setRemarks(e.getMessage());
                }

                try {
                    dingConfService.save(dingConf);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }
    }
}
